package com.example.sharingjdbc4digiwin.config;

import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.api.algorithm.sharding.RangeShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import io.shardingsphere.api.algorithm.sharding.standard.RangeShardingAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.Collection;

/**
 * @author： ygl
 * @date： 2019/06/22
 * @Description：
 */
@Slf4j
public class TablePreciseShardingAlgorithm implements PreciseShardingAlgorithm<String> {

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * @param names         匹配的库
     * @param shardingValue 对应的分片
     * @return
     */
    @Override
    public String doSharding(Collection<String> names, PreciseShardingValue<String> shardingValue) {
        log.info("分表算法参数 {},{}", names, shardingValue);
        int month = getMonth(shardingValue.getValue());
        String table = "data_day_" + month;
        log.info("对应的分表：{}", table);
        return table;
    }

    public int getMonth(String shardingKey){
        LocalDate date = LocalDate.parse(shardingKey, formatter);
        Month month = date.getMonth();
        return month.getValue();
    }

}

